Page({
  data: {
    userId: '',
    userInfo: '',
  },
  getLoginUser() {
    let token = wx.getStorageSync('token');
    // console.log('token ==> ', token);
    if (!token) {
      return;
    }
    wx.cloud.callFunction({
      name: 'get-user-login',
      data: {
        token
      }
    }).then(res => {
      let tokenData = res.result.data
      for (let i = 0; i < tokenData.length; i++) {
        if (tokenData[i].token == token) {
          this.setData({
            userId: tokenData[i].userId
          })
        }
      }
      this.getUser()
    }).catch(err => {
      console.log(err);
    })
  },
  getUser() {
    wx.cloud.callFunction({
      name: 'get-user',
      data: {
        userId: this.data.userId
      }
    }).then(res => {
      // console.log('res66 ==>', res);
      this.setData({
        userInfo: res.result.data[0]
      })
      this.getAllreceived();
      // console.log(this.data.userInfo);
    }).catch(err => {
      console.log('err66 ==> ', err);
    })
  },
  onLoad(options) {

  },
  getAllreceived() {
    wx.cloud.callFunction({
      name: 'get-All',
    }).then(res => {
      console.log('res ==>', res);
      res.result.data
      let data = [];
      for (let i = 0; i < res.result.data.length; i++) {
        for (let j = 0; j < res.result.data[i].received.length; j++) {
          data.push(res.result.data[i].received[j])
        }
      }
      console.log(data);
      for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < this.data.userInfo.request.length; j++) {
          if(data[i]._id == this.data.userInfo.request[j]._id){
            this.setData({
              ['userInfo.request['+j+']']:data[i]
            })
            wx.cloud.callFunction({
              name: 'save-request',
              data: {
                request: this.data.userInfo.request,
                userId: this.data.userId,
              },
            }).then(res => {
              console.log('res ==> ', res);
            }).catch(err => {
              console.log('err ==> ', err);
            })
          }
        }
      }
    }).catch(err => {
      console.log('err66 ==> ', err);
    })
  },
  onShow() {
    this.getLoginUser();
  },
})